import dayjs from 'dayjs';
/**
 * 计算百分比
 * @param numerator 分子
 * @param denominator 坟墓
 * @param decimal 小数位数
 * @returns 百分比
 */
export function computedRate(numerator: number, denominator: number, decimal = 0): number {
    if (!numerator) return 0;
    if (numerator === denominator) return 100;
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    return ((numerator / denominator) * 100).toFixed(decimal) as any;
}

/* eslint-disable @typescript-eslint/no-explicit-any */
type objectType = {
    [propsName: string]: any;
};

/**
 * 多层级合并对象
 * @param target 目标对象
 * @param source 合并对象
 * @returns 合并后对象
 */
export function assignRecursive(target: objectType, source: objectType) {
    if (typeof target !== 'object' || typeof source !== 'object') return source;
    for (const key in source) {
        if (Object.prototype.hasOwnProperty.call(target, key)) {
            target[key] = assignRecursive(target[key], source[key]);
        } else {
            target[key] = source[key];
        }
    }
    return target;
}

export function formatTime(time: dayjs.ConfigType, format = 'YYYY-MM-DD HH:mm'): string {
    if (!time) {
        return '-';
    }
    return dayjs(time).format(format);
}

/**
 * 等待几秒钟
 * @param second 秒
 * @returns promise
 */
export function sleepFun(second: number) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(true);
        }, second * 1000);
    });
}

/**
 * 如果是直辖市，返回3，否则空
 * @param code 省市区code值
 */
export function municipalityLevel(code: string | number | null): number | null {
    if (['110000', '120000', '500000', '310000'].includes(`${code}`)) return 3;
    return null;
}

/** 两数相乘精度问题 */
export function accMultiply(arg1: number, arg2: number) {
    let m = 0;
    const s1 = arg1.toString();
    const s2 = arg2.toString();
    try {
        m += s1.split('.')[1].length;
    } catch (e) {
        e;
    }
    try {
        m += s2.split('.')[1].length;
    } catch (e) {
        e;
    }
    return (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / Math.pow(10, m);
}
